package com.thwj.project.system.controller;

import cn.hutool.core.lang.Dict;
import com.thwj.common.constant.Constants;
import com.thwj.common.core.domain.AjaxResult;
import com.thwj.common.utils.SecurityUtils;
import com.thwj.framework.security.LoginBody;
import com.thwj.framework.web.domain.R;
import com.thwj.framework.web.service.SysLoginService;
import com.thwj.framework.web.service.SysPermissionService;
import com.thwj.project.system.domain.SysMenu;
import com.thwj.project.system.domain.SysUser;
import com.thwj.project.system.service.ISysMenuService;
import com.thwj.project.system.service.ISysUserService;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Set;

/**
 * 登录验证
 *
 * @author 可乐
 */
@RestController
//@Api(tags = "系统登录")
public class SysLoginController {

    private static final Logger logger = LoggerFactory.getLogger("sys-user");
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private ISysUserService userService;


    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody) {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo() {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters() {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }


    @PostMapping("/login/wx")
    @ApiOperation(value = "移动端微信一键登入")
    public R appLoginWx(@RequestBody LoginBody loginBody) {
        // 生成令牌
        Dict dict = loginService.servantLoginWx(loginBody.getUsername(), loginBody.getOpenId());
        return R.data(dict);
    }


   /* @ApiOperation(value = "陪玩官通过code微信一键登录")
    @GetMapping("/servant/wxLoginBycode")
    public R<Dict> servantWxLoginBycode(@RequestParam(value = "openIdCode") String openIdCode, @RequestParam(value = "phoneCode", required = false, defaultValue = "") String phoneCode) {


//        获取openId
        String result = WxUtils.getMiniOpenId(openIdCode);
        logger.info("servantWxLoginBycode:{}", result);
        if (!JSONUtil.isJsonObj(result)) {
            return R.error("获取OpenId失败");
        }
        JSONObject jsonObject = new JSONObject(result);
        boolean flag = jsonObject.isNull("errcode");
        if (!flag) {
            return R.error("获取OpenId失败");
        }
        String openId = String.valueOf(jsonObject.get("openid"));

//        获取电话号码
        String phoneNumber = "";
        if (phoneCode != "") {
            String phoneResult = WxUtils.getPhoneNumber(phoneCode);
            if (!JSONUtil.isJsonObj(result)) {
                return R.error("获取电话失败");
            }

            JSONObject phoneJson = new JSONObject(phoneResult);
            JSONObject phone_info = phoneJson.getJSONObject("phone_info");
            phoneNumber = String.valueOf(phone_info.get("purePhoneNumber"));
        }

// 生成令牌
        Dict dict = loginService.servantLoginWx(phoneNumber, openId);
        if (StringUtils.equalsIgnoreCase((String) dict.get("token"), "0")) {
            return R.error("账号已被冻结,登录失败");
        }
        return R.data(dict);

    }*/

}
